import { hasLogin } from "./localStorage";
const app = getApp()
const baseUrl = "http://localhost:8885/"
// const baseUrl = "http://119.29.162.143:8885/"
let asyncCount = 0;
const whiteList = [
  "/user/login"
]
export class WXRequest {
  defaults = {
    url: '',
    method: "",
    data: {},
    header: {
      'content-type': 'application/json' // 默认值
    }
  }
  constructor(params) {
    this.defaults = Object.assign({}, this.defaults, params)
  }
  interceptors = {
    request: (params) => {
      params = Object.assign({}, this.defaults, params)
      if (!whiteList.includes(params.url) && !Object.keys(params.data).includes("userId")) {
        const token = hasLogin()
        if (token) {
          params.data.userId = token.toString()
        }
      }
      if (params.data.resourceType === 'btm') {
        params.url = `${btmUrl}${params.url}`
      } else {
        params.url = `${baseUrl}${params.url}`
      }
      return params
    },
    response: (response) => {
      if (response.statusCode === 200) {
        return response.data
      }
      return false
    }
  }
  request(options) {
    const requestOptions = this.interceptors.request(options)
    asyncCount++
    wx.showLoading({
      title: "加载中...",
      mask: true
    })
    return new Promise((resolve, reject) => {
      wx.request({
        ...requestOptions,
        success: (res) => {
          resolve(this.interceptors.response(res))
        },
        fail: (err) => {
          console.log(err.errMsg, err.errno)
          reject(this.interceptors.response(err))
        },
        complete: () => {
          asyncCount--
          if (asyncCount === 0) {
            setTimeout(function () {
              wx.hideLoading()
            }, 200)
          }
        }
      })
    })
  }
  post(params) {
    params.method = "POST"
    return this.request(params)
  }
}